#include <filesystem> // c++17
#include <cstring>
#include <cstdlib>
#include "confrontation.hpp"
using namespace std;
namespace fs = filesystem;

// g++ -O3 -std=c++17 -o main main.cpp -lstdc++fs

void ordinary(const char *path, const char *csv_name, int csv_num, int confrontation_num)
{
    string dir_path(path);
    fs::recursive_directory_iterator it(dir_path);
    fs::recursive_directory_iterator end; // 无参构造函数是end
    for(int i = 0; i < csv_num; i++)
    {
        cout << "The number of converted XMLs:" << endl;
        confrontation conf;
        for(int j = 0; j < confrontation_num && it != end; j++, it++)
        {
            const char *file_path = it->path().c_str();
            if(fs::is_directory(file_path))
                continue;
            
            if((j & 1023) == 0)
                cout << j << endl;
            
            conf.input(file_path);
        }
        conf.output_csv(string(csv_name) + to_string(i));
    }
}

void ordinary_out_filename(const char *path, const char *csv_name, int csv_num, int confrontation_num)
{
    string dir_path(path);
    fs::recursive_directory_iterator it(dir_path);
    fs::recursive_directory_iterator end; // 无参构造函数是end
    for(int i = 0; i < csv_num; i++)
    {
        confrontation conf;
        for(int j = 0; j < confrontation_num && it != end; j++, it++)
        {
            const char *file_path = it->path().c_str();
            if(fs::is_directory(file_path))
                continue;
            cout << it->path().filename() << endl;
            conf.input(file_path);
        }
        conf.output_csv(string(csv_name) + to_string(i));
    }
}

void xue_bing()
{
    string dir_path("/mnt/h/tai");

    confrontation conf;
    for(auto &entry : fs::recursive_directory_iterator(dir_path))
    {
        const char *file_path = entry.path().c_str();
        const char *ptr = strrchr(file_path, '.') - 1;
        int perspective = *ptr - '0';
        conf.input(file_path, perspective);
    }
    conf.output_csv(string("tai"));
}

// 运行格式：./main 数据文件夹路径 生成的csv文件名前缀 生成的csv组数 单个csv所含南风局数 是否输出文件名（0为false，其余为true）
// 如 ./main /mnt/h/haifu 3W 1 30000 0
int main(int argc, char *argv[])
{
    ios::sync_with_stdio(false);

    if(argc != 6)
    {
        cout << "Invalid argument!" << endl;
        return 1;
    }

    // freopen("res.txt", "w", stdout);
    // const char *path = "/mnt/h/haifu";
    if(atoi(argv[5]) == 0)
        ordinary(argv[1], argv[2], atoi(argv[3]), atoi(argv[4]));
    else
        ordinary_out_filename(argv[1], argv[2], atoi(argv[3]), atoi(argv[4]));
    // xue_bing();

    return 0;
}